<?php
namespace App\Http\Controllers;

use App\Models\Address;
use App\Models\Store;
use App\Models\StoreVillager;
use App\Services\AdService;
use App\Services\GoodsService;
use App\Services\HotelService;
use App\Services\RestaurantsService;
use App\Services\StoreService;
use App\Services\LandownersService;
use App\Services\TourService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

/**
 *
 * 店铺控制器
 *
 * @author maqu
 *
 */
class StoreController extends BaseController {

    /**
     *
     * 获取乡村代言人
     *
     * @param $store_id 店铺ID
     * @return mixed
     */
    function getStoreVillagers($store_id){

        if(!$store_id){
            return $this->args_invalid();
        }

        $firstrow = Input::get('firstrow',0);
        $pagesize = Input::get('pagesize',10);

        $store = Store::find($store_id);

        if(!$store){
            return $this->failure('该乡村不存在');
        }

        $villagers = StoreVillager::where('store_id',$store_id)->orderBy('create_at','desc')->skip($firstrow)->take($pagesize)->get();

//        $villagers = $store->villagers;
        foreach($villagers as $v){
            $v->create_at_formatted = local_date_ymd($v->create_at);
            $v->portrait = complete_url($v->portrait);
        }

        return $this->success($villagers);

    }

    /**
     *
     *  申请乡村代言人
     *
     * @param $store_id 店铺ID
     * @return mixed
     */
    function postApplyVillagers($store_id){

        if(!$store_id){
            return $this->args_invalid();
        }

        $input = Input::all();
        $rules = array(
            'nickname'  => 'required|max:15',
            'gender'    => 'required|integer',
            'portrait'  => 'required|',
            'region'    => 'required',
            'phone_mob' => 'required',
            'slogan'    => 'required',
            'age'       => 'required'
        );

        $travelers = Validator::make($input, $rules);
        if ($travelers->fails()){
            return $this->failure($travelers->messages());
        }

        //$file = Input::file('portrait');
        $filename = gmtime() . rand(33333, 99999);
        $filepath = '/data/files/stores/' .$store_id . '/xillanger/'.$filename;
        //$portrait_path = $filepath . '.' . $file->getClientOriginalExtension();
        $portrait_path = $filepath . '.jpg';
        //$fp = fopen($_FILES["portrait"]["tmp_name"],"rb");
        //$buf = fread($fp,$_FILES["portrait"]["size"]);
        $temps = explode(',',Input::get("portrait"));
        $img = base64_decode($temps[1]);

        Storage::disk()->put( $portrait_path,$img);
//        unset($fp);
//        unset($buf);
//        unset($file);

        $nickname     = Input::get('nickname');
        $gender       = Input::get('gender');
        $portrait     = $portrait_path;
        $region       = Input::get('region');
        $phone_mob    = Input::get('phone_mob');
        $slogan       = Input::get('slogan');
        $age          = Input::get('age');

        StoreVillager::insert([
            'store_id'  => $store_id,
            'nickname'  => $nickname,
            'gender'    => $gender,
            'portrait'  => $portrait,
            'region'    => $region,
            'phone_mob' => $phone_mob,
            'slogan'    => $slogan,
            'age'       => $age,
            'create_at' => gmtime(),
        ]);

        return $this->success(null);
    }

    /**
     * 店铺首页
     *
     * @param $store_id
     * @param AdService $adService
     * @param TourService $tourService
     * @return mixed
     */
    function getIndex($store_id,AdService $adService,TourService $tourService){

        //【经纬度】
        //    lat   经度
        //    lon   维度
        $lat =Input::get('lat',999);
        $lon =Input::get('lon',999);

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
		
        $store = Store::find($store_id);
        if(!$store){
            return $this->args_invalid();
        }

        $datas = [
            'store'=>[],
            'carousels'=>[]
//            'tours'=>[]
        ];

        $store->image_1 = complete_url($store->image_1);
        $store->image_2 = complete_url($store->image_2);
        $store->image_3 = complete_url($store->image_3);
        $store->store_banner = complete_url($store->store_banner);

        $datas['store'] = $store->toArray();

        //carousels
        $result = $adService->getStoreAdByStoreId($store_id,'villager_home_mid_ad',0,7);
        if($result['result']===false){
            return $this->failure($result['msg']);
        }
        $datas['carousels']=$result['data'];

//        //tours
//        $result = $tourService->getVillagerToursByStoreId($store_id,$lat,$lon,0,10);
//        if($result['result']===false){
//            return $this->failure($result['msg']);
//        }
//        $datas['tours'] = $result['data'];
        return $this->success($datas);

    }

    /**
     * 村介绍
     * @param $store_id
     * @return mixed
     */
    function getIntro($store_id){

        if(!$store_id){
            return $this->args_invalid();
        }

        $store = Store::find($store_id);
        if(!$store){
            return $this->failure('店铺不存在');
        }
        $data=['content'=>''];
        $data['store_name'] = $store->store_name;
        $data['title'] = $store->store_name;
        $data['brief'] = $store->brief;
        $data['store_banner'] = complete_url($store->store_banner);
        $html =complete_html(config('maqu.STATIC_RESOURCE_URL'),$store->store_name,$store->description);
        $data['content']=$html;

        unset($html);

        return $this->success($data);

    }

    /**
     * 乡村合伙人介绍
     * @param $store_id
     * @return mixed
     */
    function getPartnerIntro($store_id){

        if(!$store_id){
            return $this->args_invalid();
        }

        $store = Store::find($store_id);
        if(!$store){
            return $this->failure('店铺不存在');
        }

        $data = DB::table('member')
            ->leftJoin('member_partner','member.user_id','=','member_partner.user_id')
            ->where('member.user_id',$store->user_id)
            ->select('member.user_id','member.phone_mob','member.real_name',
                'qrcode','aboutme','portrait')
            ->first();

        if(!$data){
            return $this->args_invalid();
        }

        $data->qrcode   = complete_url($data->qrcode);
        $data->portrait = complete_url($data->portrait);
        $data->aboutme  = complete_html(config('maqu.STATIC_RESOURCE_URL'),$store->owner_name,$data->aboutme);

        $data->store_banner = complete_url($store->store_banner);
        $data->owner_name = $store->owner_name;
        $data->province = $store->province;
        $data->city = $store->city;
        $data->country = $store->country;
        $data->address = $store->address;
//        $data->tel =  $str = substr_replace($store->phone_mob,'****',3,4);
        $data->tel = $data->phone_mob;
        $data->owner_name = $data->real_name;
        return $this->success($data);

    }

    /**
     * 获取村的路线列表
     *
     * @param $store_id
     * @param TourService $tourService
     * @return mixed
     */
    function getTours($store_id,TourService $tourService){

        //【经纬度】
        //    lat   经度
        //    lon   维度
        $lat =Input::get('lat',999);
        $lon =Input::get('lon',999);

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
		
        $firstrow =Input::get('firstrow',0);
        $pagesize =Input::get('pagesize',10);

        if(!$store_id){
            return $this->args_invalid();
        }

        $result = $tourService->getVillagerToursByStoreId($store_id,$lat,$lon,$firstrow,$pagesize);
        if($result['result']===false){
            return $this->failure($result['msg']);
        }

        return $this->success($result['data']?$result['data']:[]);

    }

    /**
     * 获取土特产列表
     *
     * @param $store_id
     * @param GoodsService $goodsService
     * @return mixed
     */
    function getGoods($store_id,GoodsService $goodsService){

        //【经纬度】
        //    lat   经度
        //    lon   维度
        $lat =Input::get('lat',999);
        $lon =Input::get('lon',999);

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
		
        $firstrow =Input::get('firstrow',0);
        $pagesize =Input::get('pagesize',10);

        if(!$store_id){
            return $this->args_invalid();
        }

        $result = $goodsService->getVillagerGoodsByStoreId($store_id,$lat,$lon,$firstrow,$pagesize);
        if($result['result']===false){
            return $this->failure($result['msg']);
        }

        return $this->success($result['data']?$result['data']:[]);

    }

    /**
     * 民宿列表
     *
     * @param $store_id
     * @param HotelService $hotelService
     * @return mixed
     */
    function getHotels($store_id,HotelService $hotelService){

        //【经纬度】
        //    lat   经度
        //    lon   维度
        $lat =Input::get('lat',999);
        $lon =Input::get('lon',999);
        $firstrow =Input::get('firstrow',0);
        $pagesize =Input::get('pagesize',10);

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
		
        if(!$store_id){
            return $this->args_invalid();
        }

        $result = $hotelService->getVillagerHotelsByStoreId($store_id,$lat,$lon,$firstrow,$pagesize);
        if($result['result']===false){
            return $this->failure($result['msg']);
        }

        return $this->success($result['data']?$result['data']:[]);

    }

    /**
     * 农家乐列表
     *
     * @param $store_id
     * @param RestaurantsService $restaurantsService
     * @return mixed
     */
    function getRestaurants($store_id,RestaurantsService $restaurantsService){

        //【经纬度】
        //    lat   经度
        //    lon   维度
        $lat =Input::get('lat',999);
        $lon =Input::get('lon',999);
        $firstrow =Input::get('firstrow',0);
        $pagesize =Input::get('pagesize',10);

		if($lat=='undefined'){
			$lat = 999;
		}
		if($lon=='undefined'){
			$lon = 999;
		}
        if(!$store_id){
            return $this->args_invalid();
        }

        $result = $restaurantsService->getVillagerRestaurantsByStoreId($store_id,$lat,$lon,$firstrow,$pagesize);
        if($result['result']===false){
            return $this->failure($result['msg']);
        }

        return $this->success($result['data']?$result['data']:[]);

    }

    function getLandowners($store_id){
        $lat =Input::get('lat',999);
        $lon =Input::get('lon',999);

        if($lat=='undefined'){
            $lat = 999;
        }
        if($lon=='undefined'){
            $lon = 999;
        }

        $firstrow =Input::get('firstrow',0);
        $pagesize =Input::get('pagesize',10);

        if(!$store_id){
            return $this->args_invalid();
        }
        $landownersService = new LandownersService();
        $result = $landownersService->getVillagerLandownersByStoreId($store_id,$lat,$lon,$firstrow,$pagesize);
        if($result['result']===false){
            return $this->failure($result['msg']);
        }

        return $this->success($result['data']?$result['data']:[]);
    }

}
